package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

func main() {

	http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "<h1>你好</h1>") //向response中写入，文本
	})

	//处理get请求
	http.HandleFunc("/getExample", func(w http.ResponseWriter, r *http.Request) {
		//1.关闭请求
		defer r.Body.Close()

		//2.获取url参数
		data := r.URL.Query()
		fmt.Println(data.Get("name"))
		fmt.Println(data.Get("age"))

		//3.写入response值
		answer := `{"status": "ok"}`
		w.Write([]byte(answer))
	})
	//处理post请求
	http.HandleFunc("/postExample", func(w http.ResponseWriter, r *http.Request) {
		//1. 关闭请求
		defer r.Body.Close()

		//2.1 请求类型是application/x-www-form-urlencoded时解析form数据
		r.ParseForm()
		fmt.Println(r.PostForm) // 打印form数据
		fmt.Printf("方式1：name:%v----age:%v\n", r.PostForm.Get("name"), r.PostForm.Get("age"))
		//2.2 请求类型是application/json时从r.Body读取数据
		b, err := ioutil.ReadAll(r.Body)
		if err != nil {
			fmt.Printf("read request.Body failed, err:%v\n", err)
			return
		}
		fmt.Printf("方式2：%v\n", string(b))
		answer := `{"status": "ok"}`
		w.Write([]byte(answer))
	})
	customServe := &http.Server{
		Addr:           ":8000",
		Handler:        nil,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	err := customServe.ListenAndServe() //第二个参数为nil，表示采用包变量DefaultServeMux作为处理器
	if err != nil {
		fmt.Printf("监听出错:%v", err)
	}
}
